<?php
	/**
	 * Do a SQL Query
	 *
	 * @param unknown_type $sql		The SQL Query
	 * @return unknown				The result
	 */
	function mq($sql) {
		$result = mysql_query($sql) or die('MySQL Error: '.mysql_error().'<br />Query:<br /><code>'.$sql.'</code>');
		return $result;
	}
	
	/**
	 * Do a SQL Query and return the array
	 *
	 * @param unknown_type $sql		The SQL Query
	 * @param unknown_type $type	The type (assoc, row, or array)
	 * @return unknown				The array
	 */
	function ma($sql, $type = 'assoc') {
		if(is_string($sql)) {
			$result = mq($sql);
		} else {
			$result = $sql;
		}
		if(mysql_num_rows($result)>0) {
			switch($type) {
				case 'assoc' :
					{
						$a = mysql_fetch_assoc($result);
						break;
					}
				case 'row' :
					{
						$a = mysql_fetch_row($result);
						break;
					}
				default:
					{
						$a = mysql_fetch_array($result);
						break;
					}
			}			
		} else {
			return false;
		}
		return $a;
	}
	
	/**
	 * Do a SQL Query and return a single result
	 *
	 * @param unknown_type $sql		The SQL Query
	 * @return unknown				The single result
	 */
	function sr($sql) {
		$row = ma($sql, 'row');
		return $row[0];
	}
	
	/**
	 * Count the total number of occurances in a table
	 *
	 * @param unknown_type $tablename	The name of the table
	 * @param unknown_type $args		The arguments (array("id"=>12, "name"=>'hello')
	 * @return unknown					The amount
	 */
	function total($tablename, $args = null) {
		$sql = 'SELECT COUNT(*) AS `total` FROM `'.$tablename.'`';
		if($args!=null) {
			$sql .= ' WHERE ';
			$first = true;		
			foreach($args as $key=>$val) {
				if(!$first) { $sql .= ' AND '; }
				$sql .= ' `'.$key.'` = \''.$val.'\' ';
				$first = false;
			}
		}
		$sql .= ';';
		return sr($sql);
	}
	
	/**
	 * Make a string 'safe' (strip tags, add entitities)
	 *
	 * @param unknown_type $string		The string to make safe
	 * @return unknown					Formatted string
	 */
	function makeSafe($string) {
		return htmlentities(strip_tags($string), ENT_QUOTES);		
	}
?>